package handlers;

import java.net.Socket;

import main.classes.Server;
import common.classes.HeaderWorker;
import common.classes.SessionSupporter;

public class SessionHandler extends Handler {
	private SessionSupporter sessionSuppporter;

	public SessionHandler() {
		super();
		this.sessionSuppporter = new SessionSupporter(12000);
	}

	public SessionHandler(Handler next) {
		super(next);
		this.sessionSuppporter = new SessionSupporter(12000);
	}

	public SessionHandler(Handler next, long timeLimit) {
		super(next);
		this.sessionSuppporter = new SessionSupporter(timeLimit);
	}

	@Override
	public void parseRequest(Socket socket, HeaderWorker header, String error) {
		if (error != null) {
			super.parseRequest(socket, header, error);
			return;
		}
		if (header.getcSID() == -1){
			int sid = this.sessionSuppporter.add();
			if (sid == -1) {
				super.parseRequest(socket, header, "503 Service Unavailable");
				Server.getLoger().log(-1, header.getFilePath(), false);
				return;
			}
			header.setWillCreateCookie(true);
			header.setcSID(sid);
			header.setcTime(this.sessionSuppporter.getTimeFor(sid));
		}
		super.parseRequest(socket, header, error);
	}

}
